package com.sdl.timesblogmp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdl.timesblogmp.config.ProjectConfig;
import com.sdl.timesblogmp.exception.CustomException;
import com.sdl.timesblogmp.model.entity.Uploadfile;
import com.sdl.timesblogmp.mapper.UploadfileMapper;
import com.sdl.timesblogmp.model.vo.PageParam;
import com.sdl.timesblogmp.service.UploadfileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdl.timesblogmp.utils.FileUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sdl
 * @since 2020-05-11
 */
@Service
public class UploadfileServiceImpl extends ServiceImpl<UploadfileMapper, Uploadfile> implements UploadfileService {
    @Resource
    private UploadfileMapper uploadfileMapper;
    @Override
    public Uploadfile uploadfile(MultipartFile file) {
        if (file==null){
            throw new CustomException("上传文件错误！");
        }
        Uploadfile uploadfile = FileUtil.upload(file, ProjectConfig.getPath());
        uploadfileMapper.insert(uploadfile);
        return uploadfile;
    }

    @Override
    public int deletefile(Integer id) {
        Uploadfile uploadfile = uploadfileMapper.selectById(id);
        if (uploadfile==null){
            throw new CustomException("文件不存在！");
        }
        try{
            FileUtil.deleteFile(uploadfile.getFilepath());
        }catch (Exception e){
            throw new CustomException("删除文件错误！");
        }
        int i = uploadfileMapper.deleteById(id);
        return i;
    }

    @Override
    public IPage<Uploadfile> findUploadfileInfo(PageParam pageParam) {
        if (pageParam.getPageNo()==0||pageParam.getPageSize()==0){
            pageParam.setPageNo(1);
            pageParam.setPageSize(6);
        }
        QueryWrapper<Uploadfile> wrapper = new QueryWrapper();
        if (pageParam.getName()!=null){
            wrapper.like("filename",pageParam.getName());
        }
        Page<Uploadfile> page = new Page<>(pageParam.getPageNo(),pageParam.getPageSize());
        page = uploadfileMapper.selectPage(page,wrapper);
        return page;
    }
}
